//
//  Utils.m
//  Helpers
//
//  Created by bianruifeng on 16/6/30.
//  Copyright © 2016年 bian. All rights reserved.
//

#import "Utils.h"

#import <AudioToolbox/AudioToolbox.h>
#import <AdSupport/AdSupport.h>
#import "OpenUDID.h"


#include <sys/socket.h> // Per msqr
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>


@implementation Utils


static CGRect oldFrame;

+ (void)showImage:(UIImageView *)oldImageView
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    oldFrame = [oldImageView convertRect:oldImageView.bounds toView:window];
    backgroundView.backgroundColor = [UIColor blackColor];
    backgroundView.alpha = 0;
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:oldFrame];
    imageView.image = oldImageView.image;
    imageView.tag = 1;
    [backgroundView addSubview:imageView];
    [window addSubview:backgroundView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideImage:)];
    [backgroundView addGestureRecognizer:tap];
    
    [UIView animateWithDuration:0.3 animations:^{
        imageView.frame = CGRectMake(0, ([UIScreen mainScreen].bounds.size.height - oldImageView.image.size.height * [UIScreen mainScreen].bounds.size.width / oldImageView.image.size.width) / 2, [UIScreen mainScreen].bounds.size.width, oldImageView.image.size.height * [UIScreen mainScreen].bounds.size.width / oldImageView.image.size.width);
        backgroundView.alpha = 1;
    } completion:^(BOOL finished) {
        
    }];
}

+ (void)hideImage:(UITapGestureRecognizer *)tap
{
    UIView *backgroundView = tap.view;
    UIImageView *imageView = (UIImageView*)[tap.view viewWithTag:1];
    [UIView animateWithDuration:0.3 animations:^{
        imageView.frame = oldFrame;
        backgroundView.alpha = 0;
    } completion:^(BOOL finished) {
        [backgroundView removeFromSuperview];
    }];
}



+ (UIImage *)loadImageWithPath:(NSString *)fileName
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
    return [UIImage imageWithContentsOfFile:filePath];
}


+(instancetype)sharedInstance
{
    static Utils *instance=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance =[[super allocWithZone:nil] init];
    });
    return instance;
}
//allocWithZone是创建对象分配内存的源头，alloc也会调用该接口来分配内存创建对象。
+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    return [[self class] sharedInstance];
}


FOUNDATION_EXPORT Utils *sharedInstance_NSHelper() {
    static dispatch_once_t onceToken;
    static Utils *swizzledClasses = nil;
    dispatch_once(&onceToken, ^{
        swizzledClasses = [[Utils alloc] init];
    });
    
    return swizzledClasses;
}



#pragma mark - [简单提示]
+(void)showAlertTitle:(NSString *)Title message:(NSString *)message cancel:(NSString *)cancel{
    UIAlertView *alert =[[UIAlertView alloc] initWithTitle:Title
                                                   message:message
                                                  delegate:nil
                                         cancelButtonTitle:cancel
                                         otherButtonTitles:nil];
    [alert show];
}

+(void)showAlertTitle:(NSString *)text forView:(UIView *)view
{
    
    UILabel* lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 230, 50)];
    lab.backgroundColor = [UIColor colorWithWhite:0.185 alpha:1.000];
    lab.numberOfLines=0;
    CGPoint point = view.center;
    lab.center = point;
    lab.layer.masksToBounds = YES;
    lab.layer.cornerRadius = 10;
    lab.alpha = 0;
    lab.text = text;
    lab.font = [UIFont systemFontOfSize:12];
    lab.textColor = [UIColor whiteColor];
    lab.textAlignment = NSTextAlignmentCenter;
    [view addSubview:lab];
    
    [UIView animateWithDuration:1.5 animations:^{
        lab.alpha = 1;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:3 animations:^{
            lab.alpha = 0;
        }completion:^(BOOL finished) {
            [lab removeFromSuperview];
        }];
    }];
}


//判断是否为整形：

+ (BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}
//判断是否为浮点形：

- (BOOL)isPureFloat:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return [scan scanFloat:&val] && [scan isAtEnd];
}

#pragma mark - [播放提示音]
+ (void)PlayBeep:(NSString *)Soundfilename
{
    //声音
    //需要导入框架#import <AudioToolbox/AudioToolbox.h>
    NSString *path = [[NSBundle mainBundle] pathForResource:Soundfilename ofType:@"wav"];
    NSURL *url = [NSURL fileURLWithPath:path];
    SystemSoundID soundId;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundId);
    AudioServicesPlaySystemSound(soundId);
}

+(NSString *)getCurrentTime:(NSString *)TimeStyle
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:TimeStyle];
    NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
    return strDate;
}
NSString *DocumentsPath(){
    return [Utils getDocumentsPath];
}



#pragma mark - [获得-Mac地址]
+ (NSString *) getMacAddress
{
    int                    mib[6];
    size_t                len;
    char                *buf;
    unsigned char        *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl    *sdl;
    
    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;
    
    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error/n");
        return NULL;
    }
    
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1/n");
        return NULL;
    }
    
    if ((buf = malloc(len)) == NULL) {
        printf("Could not allocate memory. error!/n");
        return NULL;
    }
    
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 2");
        return NULL;
    }
    
    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    NSString *outstring = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x",*ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    free(buf);
    return [outstring uppercaseString];
}

#pragma mark - [唯一标示]

/**
 *  获得的这个CFUUID值系统并没有存储。每次调用CFUUIDCreate，系统都会返回一个新的唯一标示符。如果你希望存储这个标示符，那么需要自己将其存储到NSUserDefaults, Keychain, Pasteboard或其它地方。
 */
+(NSString *)getCFUUID
{
    CFUUIDRef cfuuid = CFUUIDCreate(kCFAllocatorDefault);
    NSString *cfuuidString = (NSString*)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, cfuuid));
    return cfuuidString;
    //    //    方法一：
    //    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    //    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    //    NSString * result =(__bridge  NSString *)string;
    //    CFRelease(theUUID);
    //    CFRelease(string);
}
/**
 *  NSUUID在iOS 6中才出现，这跟CFUUID几乎完全一样，只不过它是Objective-C接口。+ (id)UUID 是一个类方法，调用该方法可以获得一个UUID。通过下面的代码可以获得一个UUID字符串：
 */
+(NSString *)getNSUUID
{
    NSString *uuid = [[NSUUID UUID] UUIDString];
    return uuid;
}
/**
 *  广告标识符   跟CFUUID和NSUUID不一样，广告标示符是由系统存储着的。不过即使这是由系统存储的，但是有几种情况下，会重新生成广告标示符。如果用户完全重置系统（(设置程序 -> 通用 -> 还原 -> 还原位置与隐私) ，这个广告标示符会重新生成。另外如果用户明确的还原广告(设置程序-> 通用 -> 关于本机 -> 广告 -> 还原广告标示符) ，那么广告标示符也会重新生成。关于广告标示符的还原，有一点需要注意：如果程序在后台运行，此时用户“还原广告标示符”，然后再回到程序中，此时获取广告标示符并不会立即获得还原后的标示符。必须要终止程序，然后再重新启动程序，才能获得还原后的广告标示符。之所以会这样，我猜测是由于ASIdentifierManager是一个单例。
 */
//导入AdSupport.framework
+(NSString *)getADID
{
    NSString *adid = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    return adid;
}
/**
 *  供应商标识符，当CFBundleIdentifier（反转DNS格式）的前两部分。例如，com.apple.app1 和 com.apple.app2 得到的identifierForVendor是相同的，因为它们的CFBundleIdentifier 前两部分是相同的.当重新安装此供应商的应用时 标识符会被重置
 */
+(NSString *)getVDID
{
    NSString *idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    return idfv;
}
/**
 *  开放标识符  OpenUDID利用了一个非常巧妙的方法在不同程序间存储标示符 — 在粘贴板中用了一个特殊的名称来存储标示符。通过这种方法，别的程序（同样使用了OpenUDID）知道去什么地方获取已经生成的标示符（而不用再生成一个新的）。
 */
+(NSString *)getOpenUDID
{
    return [OpenUDID value];
}

+(NSArray *)getFilenamelistOfType:(NSString *)type fromDirPath:(NSString *)dirPath
{
    
    NSArray *fileList = [[[NSFileManager defaultManager] contentsOfDirectoryAtPath:dirPath error:nil] pathsMatchingExtensions:[NSArray arrayWithObject:type]];
    
    return fileList;
}

/**
 *  遍历 获得此Directory下所有文件名
 */
+ (NSArray *)getAllFileAtPath:(NSString *)filePath
{
    NSFileManager *fileManage = [NSFileManager defaultManager];
//    NSArray *file = [fileManage subpathsOfDirectoryAtPath:filePath error:nil];//作用同下
    NSArray *files = [fileManage subpathsAtPath:filePath];
    return files;
}
/**
 * 判断文件是否存在
 */
+ (BOOL)isFileExists:(NSString *)filepath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager fileExistsAtPath:filepath];
}

+ (NSString *)CreateFileAtPath:(NSString *)filePath Success:(void(^)())Success Error:(void(^)(int error))error{
    //查找文件，如果不存在，就创建一个文件
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![self isFileExists:filePath]){
        if ([fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil]){
            Success();
            return filePath;
        }
        else{
            //失败
            error(0);
        }
    }
    return filePath;
}

#pragma mark - [获取文件大小]
+ (float) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize]/(1024.0*1024);;
    }
    return 0;
}

#pragma mark - [延时回调]
+ (void)performBlock:(void (^)(void))block afterDelay:(NSTimeInterval)delay
{
    [self performSelector:@selector(fireBlockAfterDelay:) withObject:block afterDelay:delay];
}
+ (void)fireBlockAfterDelay:(void (^)(void))block
{
    block();
}
//-(IBAction) CreateFile
//{
//    //对于错误信息
//    NSError *error;
//    // 创建文件管理器
////    NSFileManager *fileMgr = [NSFileManager defaultManager];
//    NSFileManager *fileManager = [[NSFileManager alloc]init];
//
//    //指向文件目录
//
//    NSString *documentsDirectory= [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//    //创建一个目录
//    [[NSFileManager defaultManager] createDirectoryAtPath: [NSString stringWithFormat:@"%@/myFolder", NSHomeDirectory()] attributes:nil];
//    // File we want to create in the documents directory我们想要创建的文件将会出现在文件目录中
//    // Result is: /Documents/file1.txt结果为：/Documents/file1.txt
//
//    NSString *filePath= [documentsDirectory stringByAppendingPathComponent:@"file2.txt"];
//    //需要写入的字符串
//    NSString *str= @"iPhoneDeveloper Tips\nhttp://iPhoneDevelopTips,com";
//    //写入文件
//    [str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
//    //显示文件目录的内容
//    NSLog(@"Documentsdirectory: %@",[fileManager contentsOfDirectoryAtPath:documentsDirectory error:&error]);
//}

/**
 *  压缩视频
 *
 *  @param inputUrl  视频输入地址
 *  @param outputUrl 视频输出地址
 *  @param handler   压缩完毕回调
 */
+ (void)videoCompressQualityWithInputUrl:(NSURL *)inputUrl
                               outputUrl:(NSURL *)outputUrl
                            blockHandler:(void(^)(AVAssetExportSession *session))handler
{
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:inputUrl options:nil];
    AVAssetExportSession *session = [[AVAssetExportSession alloc]initWithAsset:asset presetName:AVAssetExportPresetMediumQuality];
    //    [[NSFileManager defaultManager] removeItemAtURL:outputUrl error:nil];
    session.outputURL = outputUrl;
    session.outputFileType = AVFileTypeMPEG4;
    
    [session exportAsynchronouslyWithCompletionHandler:^(void)
     {
         switch (session.status) {
             case AVAssetExportSessionStatusUnknown:
                 NSLog(@"AVAssetExportSessionStatusUnknown");
                 break;
             case AVAssetExportSessionStatusWaiting:
                 NSLog(@"AVAssetExportSessionStatusWaiting");
                 break;
             case AVAssetExportSessionStatusExporting:
                 NSLog(@"AVAssetExportSessionStatusExporting");
                 break;
             case AVAssetExportSessionStatusCompleted:
                 NSLog(@"AVAssetExportSessionStatusCompleted");
                 break;
             case AVAssetExportSessionStatusFailed:
                 NSLog(@"AVAssetExportSessionStatusFailed");
                 break;
             case AVAssetExportSessionStatusCancelled:
                 NSLog(@"AVAssetExportSessionStatusCancelled");
                 break;
             default:
                 break;
         }
         handler(session);
     }];
    
}

#pragma mark - [获得路径]

+ (NSString *)NSHomeDirectoryPath
{
    NSString *path = NSHomeDirectory();
    return path;
}
/**
 * 获得Documents路径
 */
+(NSString *)getDocumentsPath {
    NSString *DocumentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    return DocumentPath;
}
/**
 * 获得Caches缓存文件路径
 */
+(NSString *)getCachesPath{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    return path;
}
/**
 * 获得Librarys缓存文件路径
 */
+(NSString *)getLibrarysPath{
    NSArray *LibrarysPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *path=[LibrarysPaths objectAtIndex:0];
    return path;
}

//程序退出后此路径下的东西消失
+(NSString *)getTempPath{
    NSString *path = NSTemporaryDirectory();
    return path;
}

#pragma mark - /*****************************ui******************[分割线]*****************************************************/
+ (NSString *)documentPath {
    return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
}

#pragma mark - 获取缓存路径
+ (NSString *)cachePath {
    return [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
}

+ (NSString *)imageCachePath {
    NSString *path = [[self cachePath] stringByAppendingPathComponent:@"Images"];
    BOOL isDir = NO;
    BOOL isDirExist = [[NSFileManager defaultManager] fileExistsAtPath:path
                                                           isDirectory:&isDir];
    if (!isDir && !isDirExist) {
        BOOL isSuccess = [[NSFileManager defaultManager] createDirectoryAtPath:path
                                                   withIntermediateDirectories:YES
                                                                    attributes:nil error:nil];
        if (isSuccess) {
            NSLog(@"success");
        }
    }
    
    return path;
}

+ (NSString *)localShoppingCartPath {
    return [[self cachePath] stringByAppendingPathComponent:@"/cart.plist"];
}


#pragma mark - 根据文件名返回路径
+ (NSString *)pathWithFileName:(NSString *)fileName {
    return [self pathWithFileName:fileName ofType:nil];
}

+ (NSString *)pathWithFileName:(NSString *)fileName ofType:(NSString *)type {
    return [[NSBundle mainBundle] pathForResource:fileName ofType:type];
}



+ (NSString *)dateWithSeconds:(NSUInteger)seconds {
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:seconds];
    NSString *str = [NSString stringWithFormat:@"%@", date];
    NSArray *array = [str componentsSeparatedByString:@" "];
    NSString *result = [array objectAtIndex:0];
    if (array.count == 3) {
        result = [NSString stringWithFormat:@"%@ %@", result, [array objectAtIndex:1]];
    }
    return result;
}

#pragma mark - /*****************************ui******************[分割线]*****************************************************/


+(NSString *)CreateFileAtPath:(NSString *)filePath fileName:(NSString *)name
{
    
    NSString *testPath = [filePath stringByAppendingPathComponent:name];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *string = @"写入内容，write String";
    [fileManager createFileAtPath:testPath contents:[string  dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
    return nil;
}
#pragma mark - 获取JSON数据
// 把对象转换成JSON格式数据，如果转换失败，返回nil
+ (NSMutableData *)JSONDataWithObject:(id)object {
    NSMutableData *postBodyData = nil;
    if ([NSJSONSerialization isValidJSONObject:object]) {
        NSError *error = nil;
        NSData *postData = [NSJSONSerialization dataWithJSONObject:object
                                                           options:NSJSONWritingPrettyPrinted
                                                             error:&error];
        if (error) {
            NSLog(@"error: %@", error.description);
        } else {
            postBodyData = [[NSMutableData alloc] initWithData:postData];
        }
    }
    return postBodyData;
}

#pragma mark - 获取最新版本
+ (NSString *)obtainLatestAppVersion {
    // NSString *urlPath = [NSString stringWithFormat:@"http://itunes.apple.com/lookup?id=%@", kAppIDInAppStore];
    NSString *latestVersion = nil;
    NSDictionary *jsonData = nil; // 这里需要从网络请求到，这里只是写成nil，在发布后再实现
    NSArray *infoArray = [jsonData objectForKey:@"results"];
    if([infoArray count] > 0) {
        NSDictionary *releaseInfo = [infoArray objectAtIndex:0];
        latestVersion = [releaseInfo objectForKey:@"version"];
        
        // 在以前返回的值是如下格式："4.0"，后来变成了："V4.0",所以需要去掉非数值字符。
        latestVersion = [latestVersion stringByTrimmingCharactersInSet:[NSCharacterSet letterCharacterSet]];
    }
    
    return latestVersion;
}

#pragma mark - 保存应用在AppStore上的版本号到本地
+ (void)saveAppStoreVersionToUserDefaults {
    NSString *storeVersion = [[NSUserDefaults standardUserDefaults] stringForKey:kAppStoreVersionKey];
    NSString *bundleVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    
    // 应用当前的version，应该小于等于store上的version。如果不是，则说明应用升级后，
    // UserDefault中保存的store version未更新，需重新设。
    if(nil == storeVersion || [self version:bundleVersion isBiggerThan:storeVersion])
    {
        storeVersion = [self obtainLatestAppVersion]; // 获取最新的版本
        if (storeVersion) {
            [[NSUserDefaults standardUserDefaults] setObject:storeVersion forKey:kAppStoreVersionKey];
        }
    }
    return;
    
}

#pragma mark - 是否需要更新应用
+ (BOOL)isAppNeedToUpdate:(BOOL)needNetwork {
    NSString *version = nil;
    if (needNetwork) { // 获取应用在appStore上的版本
        version = [self obtainLatestAppVersion];
        if (version) { // 保存到本地
            [[NSUserDefaults standardUserDefaults] setObject:version forKey:kAppStoreVersionKey];
        }
    } else { // 直接从本地获取
        version = [[NSUserDefaults standardUserDefaults] stringForKey:kAppStoreVersionKey];
    }
    
    if (!version) {
        return NO;
    }
    
    NSString *bundleVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    if ([self version:version isBiggerThan:bundleVersion]) {
        return YES;
    }
    return NO;
}

+ (BOOL)version:(NSString *)versionA isBiggerThan:(NSString *)versionB {
    NSArray *a = [versionA componentsSeparatedByString:@"."];
    NSArray *b = [versionB componentsSeparatedByString:@"."];
    
    unsigned aa = [[a objectAtIndex:0] intValue];
    unsigned ab = [a count] > 1 ? [[a objectAtIndex:1] intValue] : 0;
    unsigned cc = [a count] > 2 ? [[a objectAtIndex:2] intValue] : 0;
    
    unsigned ba = [[b objectAtIndex:0] intValue];
    unsigned bb = [b count] > 1 ? [[b objectAtIndex:1] intValue] : 0;
    unsigned bc = [b count] > 2 ? [[b objectAtIndex:2] intValue] : 0;
    
    return ((aa > ba) || (aa == ba && ab > bb) || (aa == ba && ab == bb && cc > bc));
}

// 参数是要判断的应用的URLSchemes
+ (BOOL)hadInstallApp:(NSString *)urlSchemes {
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlSchemes]]) {
        return YES;
    }
    return NO;
}

// 能否打开应用
+ (BOOL)canOpenApp:(NSString *)itunesUrlString {
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:itunesUrlString]]) {
        return YES;
    }
    return NO;
}

+ (void)openApp:(NSString *)urlSchemes {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlSchemes]];
    return;
}

#pragma mark - 进入AppStore应用
+ (void)goToAppStoreWithURLString:(NSString *)itunesUrlString {
#if TARGET_IPHONE_SIMULATOR
    NSLog(@"虚拟机不支持APP Store.打开iTunes不会有效果。");
#else
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:itunesUrlString]];
#endif
    return;
}

#pragma mark - - [读取文件]

//读取工程文件
+(NSString *) ProductPath:(NSString*)filename{
    NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@""];
    return  path;
}





#pragma mark - [写入文件]

#pragma mark 保存图片至沙盒
+ (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 1);
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}

//写入文件存放到工程位置NSDictionary
+(void)saveNSDictionaryForProduct:(NSDictionary *)list  FileUrl:(NSString*) FileUrl{
    NSString *ProductPath =[[NSBundle mainBundle]  resourcePath];
    NSString *f=[ProductPath stringByAppendingPathComponent:FileUrl];
    [list writeToFile:f atomically:YES];
}
//将date时间戳转变成时间字符串
//@paaram   date            用于转换的时间
//@param    formatString    时间格式(yyyy-MM-dd HH:mm:ss)
//@return   NSString        返回字字符如（2012－8－8 11:11:11）
+ (NSString *)getDateStringWithDate:(NSDate *)date DateFormat:(NSString *)formatString
{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:formatString];
    NSString *dateString = [dateFormat stringFromDate:date];
    NSLog(@"date: %@", dateString);
    return dateString;
}
//将本地日期字符串转为UTC日期字符串
//本地日期格式:2013-08-03 12:53:51
//可自行指定输入输出格式
-(NSString *)getUTCFormateLocalDate:(NSString *)localDate
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //输入格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *dateFormatted = [dateFormatter dateFromString:localDate];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    [dateFormatter setTimeZone:timeZone];
    //输出格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    NSString *dateString = [dateFormatter stringFromDate:dateFormatted];
    
    return dateString;
}

//将UTC日期字符串转为本地时间字符串
//输入的UTC日期格式2013-08-03T04:53:51+0000
-(NSString *)getLocalDateFormateUTCDate:(NSString *)utcDate
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //输入格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
    [dateFormatter setTimeZone:localTimeZone];
    
    NSDate *dateFormatted = [dateFormatter dateFromString:utcDate];
    //输出格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:dateFormatted];
    return dateString;
}


@end


@implementation DeviceInformation
- (NSString *)Name
{
    return [[UIDevice currentDevice] name];
}
- (NSString *)SysVersion
{
    return [[UIDevice currentDevice] systemVersion];
}
- (NSString *)SysName
{
    return [[UIDevice currentDevice] systemName];
}
- (NSString *)OS_Version
{
    UIDevice *Device=[UIDevice currentDevice];
    return [NSString stringWithFormat:@"%@ %@",[Device systemName],[Device systemVersion]];
}
- (NSString *)DeviceModel
{
    return [[UIDevice currentDevice] model];
}
- (NSString *)ThisSoftVersion
{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    return [infoDictionary objectForKey:@"CFBundleShortVersionString"];
}

+(instancetype)sharedInstance
{
    static DeviceInformation *instance=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance =[[super allocWithZone:nil] init];
    });
    return instance;
}
//allocWithZone是创建对象分配内存的源头，alloc也会调用该接口来分配内存创建对象。
+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    return [[self class] sharedInstance];
}
@end
